<template>
  <Dialog
    :title="dialogTitle"
    v-model="dialogVisible"
    style="min-width: 860px"
    scroll
    :max-height="600"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="餐谱名称" prop="recipeName">
        <el-input v-model="formData.recipeName" placeholder="请输入餐谱名称" />
      </el-form-item>
      <!--<el-form-item label="餐谱编号" prop="recipeName">-->
      <!--  <el-input v-model="formData.recipeName" placeholder="请输入餐谱编号" />-->
      <!--</el-form-item>-->
      <el-form-item label="航空公司" prop="airlineId">
        <el-select v-model="formData.airlineId" placeholder="请选择所属航空公司" class="w-1/1">
          <el-option
            v-for="item in getIntDictOptions(DICT_TYPE.PPLAN_AIRLINE_ID)"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="航线类型" prop="airlineType">
        <el-select v-model="formData.airlineType" placeholder="请选择航线类型" class="w-1/1">
          <el-option
            v-for="item in getStrDictOptions(DICT_TYPE.PPLAN_AIRLINE_TYPE)"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="舱位等级" prop="cabinClass">
        <el-select v-model="formData.cabinClass" placeholder="请选择舱位等级" class="w-1/1">
          <el-option
            v-for="item in getStrDictOptions(DICT_TYPE.PPLAN_AIRLINE_CLASS)"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="餐食类别" prop="mealService">
        <el-select v-model="formData.mealService" placeholder="请选择餐食类别" class="w-1/1">
          <el-option
            v-for="item in getStrDictOptions(DICT_TYPE.PPLAN_MEAL_SERVICE)"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="对应套餐" prop="mealSet">
        <el-select v-model="formData.mealSet" placeholder="请选择对应套餐" class="w-1/1">
          <el-option
            v-for="item in getStrDictOptions(DICT_TYPE.PPLAN_MEAL_SET)"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <div v-for="(item, index) in formData.recipeDetailRespVOs" :key="index" style="display: flex">
        <!-- 菜品名称 -->
        <el-form-item
          label="菜品名称"
          :prop="`recipeDetailRespVOs[${index}].receipeMealId`"
          :rules="{ required: true, message: '菜品名称不能为空', trigger: 'blur' }"
          style="flex: 1"
        >
          <el-select v-model="item.receipeMealId" filterable placeholder="请选择菜品">
            <el-option
              v-for="dish in RecipeMealList"
              :key="dish.id"
              :label="dish.mealName"
              :value="dish.id"
            />
          </el-select>
        </el-form-item>

        <!-- 餐具 -->
        <el-form-item
          label="餐具"
          label-width="70px"
          :prop="`recipeDetailRespVOs[${index}].tablewareId`"
          :rules="{ required: true, message: '餐具不能为空', trigger: 'blur' }"
          style="flex: 1"
        >
          <el-select v-model="item.tablewareId" placeholder="请选择餐具" filterable>
            <el-option
              v-for="tableware in TablewareList"
              :key="tableware.id"
              :label="tableware.name"
              :value="tableware.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="配餐比例"
          :prop="`recipeDetailRespVOs[${index}].ratio`"
          :rules="[
            { required: true, message: '配餐比例不能为空', trigger: 'blur' },
            {
              validator: (rule, value, callback) => {
                const ratio = parseFloat(value)
                if (isNaN(ratio) || ratio < 0 || ratio > 100) {
                  return callback(new Error('配餐比例必须在0-100之间'))
                }
                callback()
              },
              trigger: ['blur', 'change']
            }
          ]"
          style="flex: 1"
        >
          <el-input
            type="number"
            min="0"
            max="100"
            v-model="item.ratio"
            validate-event
            placeholder="请输入配餐比例"
          />
        </el-form-item>

        <!-- 删除按钮 -->
        <el-button
          style="
            position: relative;
            top: 0px;
            margin-left: 10px;
            visibility: hidden;
            pointer-events: none;
          "
          type="danger"
          v-if="index == 0"
        >
          <Icon icon="ep:delete" />
        </el-button>
        <el-button
          v-else
          style="position: relative; top: 0px; margin-left: 10px"
          type="danger"
          @click="removeDishRow(index)"
        >
          <Icon icon="ep:delete" />
        </el-button>
      </div>
      <!-- 添加行按钮 -->
      <div style="text-align: center; margin: 10px 0">
        <el-button @click="addDishRow"><Icon icon="ep:plus" class="mr-5px" /> 添加一行</el-button>
      </div>
      <el-form-item label="是否启用" prop="isActive">
        <el-radio-group v-model="formData.isActive">
          <el-radio
            v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
            :key="dict.value"
            :value="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="有效期" prop="expireDate">
        <el-date-picker
          v-model="formData.expireDate"
          value-format="YYYY-MM-DD"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { RecipeApi, RecipeVO } from '@/api/pplan/recipe'
import { RecipeMealApi, RecipeMealVO } from '@/api/pplan/recipemeal'
import { TablewareApi, TablewareVO } from '@/api/pplan/tableware'
import { DICT_TYPE, getBoolDictOptions, getIntDictOptions, getStrDictOptions } from '@/utils/dict'
import { formatDate } from '@/utils/formatTime'

/** 生产计划-餐谱数据管理 表单 */
defineOptions({ name: 'RecipeForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  recipeCode: undefined,
  recipeName: undefined,
  airlineId: undefined,
  airlineType: undefined,
  cabinClass: undefined,
  mealService: undefined,
  mealSet: undefined,
  isActive: true,
  startDate: new Date(),
  endDate: new Date(),
  expireDate: ['2025-06-30', '2025-08-30'],
  remarks: undefined,
  recipeDetailRespVOs: [
    {
      id: undefined,
      recipeId: undefined, // 餐谱ID
      receipeMealId: undefined, // 菜品ID
      tablewareId: undefined, // 餐具ID
      ratio: undefined // 配餐比例
    }
  ] // 默认一行数据
})
const formRules = reactive({
  recipeCode: [{ required: true, message: '餐谱编号不能为空', trigger: 'blur' }],
  recipeName: [{ required: true, message: '餐谱名称不能为空', trigger: 'blur' }],
  airlineId: [{ required: true, message: '所属航空公司不能为空', trigger: 'blur' }],
  airlineType: [{ required: true, message: '航线类型不能为空', trigger: 'change' }],
  cabinClass: [{ required: true, message: '舱位等级不能为空', trigger: 'blur' }],
  mealService: [{ required: true, message: '餐食类别不能为空', trigger: 'blur' }],
  mealSet: [{ required: true, message: '对应套餐不能为空', trigger: 'blur' }],
  isActive: [{ required: true, message: '是否启用不能为空', trigger: 'blur' }],
  // startDate: [{ required: true, message: '有效期开始不能为空', trigger: 'blur' }],
  // endDate: [{ required: true, message: '有效期结束不能为空', trigger: 'blur' }],
  expireDate: [{ required: true, message: '有效期不能为空', trigger: 'blur' }],
  recipeDetailRespVOs: [
    {
      validator: (rule, value, callback) => {
        // 遍历每一行检查
        for (let i = 0; i < value.length; i++) {
          const row = value[i]
          // 校验菜品名称
          if (!row.receipeMealId) {
            return callback(new Error(`第 ${i + 1} 行：菜品名称不能为空`))
          }
          // 校验餐具
          if (!row.tablewareId) {
            return callback(new Error(`第 ${i + 1} 行：餐具不能为空`))
          }
          // 校验配餐比例
          if (!row.ratio) {
            return callback(new Error(`第 ${i + 1} 行：配餐比例不能为空`))
          }
        }
        callback() // 所有行校验通过
      },
      trigger: ['blur', 'change']
    }
  ]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  // 确保菜品列表和餐具列表初始化存在数据
  dialogVisible.value = true
  await getRecipeMealList('')
  await getTablewareList('')
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await RecipeApi.getRecipe(id)
      formData.value.expireDate = [
        formatDate(new Date(formData.value.startDate), 'YYYY-MM-DD'),
        formatDate(new Date(formData.value.endDate), 'YYYY-MM-DD')
      ]
    } finally {
      formLoading.value = false
      if (!formData.value.recipeDetailRespVOs) {
        formData.value.recipeDetailRespVOs = []
      }
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 获取菜品列表 */
const RecipeMealList = ref<RecipeMealVO[]>([]) // 菜品列表
const getRecipeMealList = async (query: String) => {
  try {
    const data = await RecipeMealApi.getRecipeMealSimpleList(query)
    RecipeMealList.value = data
  } finally {
  }
}

/** 获取餐具列表 */
const TablewareList = ref<TablewareVO[]>([]) // 菜品列表
const getTablewareList = async (query: String) => {
  try {
    const data = await TablewareApi.getTablewareSimpleList(query)
    TablewareList.value = data
  } finally {
  }
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as RecipeVO
    if (formType.value === 'create') {
      await RecipeApi.createRecipe(data)
      message.success(t('common.createSuccess'))
    } else {
      await RecipeApi.updateRecipe(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    recipeCode: undefined,
    recipeName: undefined,
    airlineId: undefined,
    airlineType: undefined,
    cabinClass: undefined,
    mealService: undefined,
    mealSet: undefined,
    isActive: true,
    startDate: new Date(),
    endDate: new Date(),
    expireDate: [],
    remarks: undefined,
    recipeDetailRespVOs: [
      {
        id: undefined,
        recipeId: undefined, // 餐谱ID
        receipeMealId: undefined, // 菜品ID
        tablewareId: undefined, // 餐具ID
        ratio: undefined // 配餐比例
      }
    ] // 重置时保留默认一行数据
  }
  formRef.value?.resetFields()
}

/** 添加一行菜品数据 */
const addDishRow = () => {
  formData.value.recipeDetailRespVOs.push({
    id: undefined,
    recipeId: formData.value.id, // 餐谱ID
    receipeMealId: undefined, // 菜品ID
    tablewareId: undefined, // 餐具ID
    ratio: undefined // 配餐比例
  })
}

/** 删除指定索引的菜品行数据 */
const removeDishRow = (index: number) => {
  formData.value.recipeDetailRespVOs.splice(index, 1)
}

onMounted(() => {})
</script>

<style scoped>
.el-select-dropdown__loading {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100px;
  font-size: 20px;
}

.circular {
  display: inline;
  height: 30px;
  width: 30px;
  animation: loading-rotate 2s linear infinite;
}
.path {
  animation: loading-dash 1.5s ease-in-out infinite;
  stroke-dasharray: 90, 150;
  stroke-dashoffset: 0;
  stroke-width: 2;
  stroke: var(--el-color-primary);
  stroke-linecap: round;
}
</style>